package com.wjd.wshow.service.impl;

import com.wjd.wshow.common.resource.Resource;
import com.wjd.wshow.common.resource.ResourceType;
import com.wjd.wshow.common.resource.entity.EntityResource;
import com.wjd.wshow.common.resource.loader.ResourceLoader;
import com.wjd.wshow.config.ContextHolder;
import com.wjd.wshow.entity.ResourceEntity;
import com.wjd.wshow.repository.BaseRepository;
import com.wjd.wshow.service.CatalogService;
import com.wjd.wshow.service.ResourceService;

public abstract class ResourceServiceImpl<T extends ResourceEntity> extends BaseServiceImpl<T, String> implements ResourceService<T> {

    /**
     * 获取资源类型
     * @return 资源类型
     */
    protected abstract ResourceType getResourceType();

    protected CatalogService getCatalogService() {
        return (CatalogService) ContextHolder.getInstance().getBean("CatalogService");
    }

    @Override
    public T create(T entity) {
        BaseRepository<T, String> repository = getRepository();
        if (repository == null) {
            return null;
        }
        T result = repository.save(entity);
        // 添加资源到目录中
        Resource resource = getResource(result.getId());
        getCatalogService().createCatalog(resource);
        return result;
    }

    @Override
    public void deleteById(String id) {
        BaseRepository<T, String> repository = getRepository();
        if (repository == null) {
            return;
        }
        // 删除在目录中的资源
        deleteResource(id);
        getCatalogService().deleteByResId(id);
        repository.deleteById(id);
    }

    @Override
    public void delete(T entity) {
        BaseRepository<T, String> repository = getRepository();
        if (repository == null) {
            return;
        }
        // 删除在目录中的资源
        getCatalogService().deleteByResId(entity.getId());
        repository.delete(entity);
    }

    @Override
    public Resource getResource(String id) {
        EntityResource<T> entityResource;
        T entity = get(id);
        entityResource = new EntityResource<>(entity);
        return entityResource;
    }

    @Override
    public void deleteResource(String id) {
        Resource resource = getResource(id);
        if (resource == null) {
            return;
        }
        ResourceLoader.getLoader().deleteResource(resource);
    }
}
